var options;

function getMilliseconds(ctrl) {
	var value = parseFloat(ctrl.val());
	value = isNaN(value) ? 0 : value * 1000;
	ctrl.val(value / 1000);
	return value;
}

// Saves options to localStorage for Zoomer.
function saveOptions() {
	options.disableZoomer = $('#disable_zoomer')[0].checked;
	_trackOption('Image Zoomer Disabled', options.disableZoomer);
	options.showCaptions = $('#showCaptions')[0].checked;
	_trackOption('Image Zoomer Captions', options.showCaptions);
	options.actionKey = $('#actionKey')[0].checked ? parseInt($('#selActionKey').val()) : 0;
	_trackOption('Image Zoomer Action Key', options.actionKey);
	options.addToHistory = $('#addToHistory')[0].checked;
	_trackOption('Image Zoomer History', options.addToHistory);
	
	localStorage.options = JSON.stringify(options);
	enableZoomerControls(false);
	sendOptions(options);
	restoreOptions();
	alert('Options saved.\nSome settings may need a page refresh.');
}

// Restores options from localStorage for Zoomer.
function restoreOptions() {
	options = loadOptions();
	$('#showCaptions')[0].checked = options.showCaptions;
	$('#actionKey')[0].checked = options.actionKey != 0;
	$('#addToHistory')[0].checked = options.addToHistory;
	
	var selActionKey = $('#selActionKey')[0];
	for (i=0; i<selActionKey.options.length; i++) {
		if (selActionKey.options[i].value == options.actionKey) {
			selActionKey.options[i].selected = true;
		}
	}
	enableZoomerControls(false);
	$('#disable_zoomer')[0].checked = options.disableZoomer;
	disableZoomer(options.disableZoomer);
}

// Disable Zoomer in case of low band-width
function disableZoomer(disabled) {
	options.disableZoomer = disabled;
	$('#selActionKey')[0].disabled = disabled ? disabled : !$('#actionKey')[0].checked;
	$('#actionKey')[0].disabled = disabled;
	$('#showCaptions')[0].disabled = disabled;
	$('#addToHistory')[0].disabled = disabled;
}

// Enable buttons on input change.
function enableZoomerControls(enabled) {
	enabled = enabled || false;
	$('#btnSave').attr('disabled', !enabled);
	$('#selActionKey')[0].disabled = options.disableZoomer ? options.disableZoomer : !$('#actionKey')[0].checked;
}

// Add event listener to input controls.
$(function() {
	$('#ZoomerOptions input, #ZoomerOptions select').change(enableZoomerControls).keydown(enableZoomerControls);
	restoreOptions();
});
